/* eslint-disable @typescript-eslint/no-unused-vars */
import { delAlarm, getAlarmList, getDeviceAlarmConfig, processAlarm } from "@/api/modules/iot/alarm";
import DialogBox from "@/components/DialogBox";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import AlarmLevel from "@/components/Sansan/Model/components/AlarmLevel";
import { MessageType } from "@/enums/messageEnum";
import { dataFormat, duration } from "@/utils/format";
import { showMsg, showTips } from "@/utils/util";
import { dayjs } from "element-plus";
import AlarmSearch from "./alarm-search";
import { IAlarmParam, useAlarmMode } from "./../../../../hooks/useAlarmParam";
import { alarmParam } from "@/utils/constants";
import { gotoPage } from "@/utils/routerUtil";
import { RouterPath } from "@/enums/routerPath";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import ConfigDetail from "./configDetail";
import SensorHistory from "@/components/Sansan/Model/device/SensorHistory";
import { JsonSchemaEmitParam } from "@/components/JsonSchemaForm/interface/jsonschema";
import { DataPreview } from "@/enums/dataPreview";
import { ElMessage, ElMessageBox } from "element-plus";
import { ComponentInternalInstance, getCurrentInstance } from "vue";
export default defineComponent({
	setup() {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		const dicts = reactive({
			...alarmParam
		});
		const sensorHistoryEl = ref();
		const loadSensorData = (row: any) => {
			let arr = row.varKey.split(".");
			let param: JsonSchemaEmitParam = {
				dataType: DataPreview.historyChart.type,
				dataPath: row.varKey,
				dataKey: arr[arr.length - 1],
				dataValue: row.varValue,
				schemaInfo: { title: row.varName }
			};
			sensorHistoryEl.value.loadData(param, row.devSn);
		};
		const initParam = reactive<any>({
			collapsed: true
		});
		const proTable = ref<any>();
		const columns: ColumnProps[] = [
			{ type: "selection", fixed: "left", width: "auto" },
			{ prop: "alarmType", label: proxy?.$t("realalarm.tablist_label.alarm_type"), width: 150 },
			{ prop: "devSn", label: proxy?.$t("realalarm.tablist_label.dev_sn"), width: 150, search: { el: "input" } },
			{ prop: "varName", label: proxy?.$t("realalarm.tablist_label.var_name"), width: 150 },
			{ prop: "varValue", label: proxy?.$t("realalarm.tablist_label.alarm_value") },
			{ prop: "createTime", label: proxy?.$t("realalarm.tablist_label.create_time"), width: 170, search: { el: "date-picker" } },
			{ prop: "duration", label: proxy?.$t("realalarm.tablist_label.duration") },
			{ prop: "level", label: proxy?.$t("realalarm.tablist_label.level"), width: "100" },
			{ prop: "reason", label: proxy?.$t("realalarm.tablist_label.reason") },
			{ prop: "operation", label: proxy?.$t("realalarm.tablist_label.operation"), fixed: "right", width: 130, isShow: false }
		];
		const buttonsList = ref<any>([]);
		onMounted(async () => {
			// 获取页面按钮权限
			buttonsList.value = await useAuthButtons();
			buttonsList.value.map((item: any) => {
				columns[columns.length - 1]["isShow"] = item.path == "execute";
			});
		});
		const dataCallback = (data: any) => {
			return {
				datalist: data.records,
				total: data.total || 0,
				pageIndex: data.current,
				pageSize: data.size
			};
		};
		const getTableList = async (params: any) => {
			return getAlarmList({ ...params, processStatus: false });
			// return { result: { records: [{}] } };
		};
		const handerBtn = (fn: string, row: any) => {
			let selected = row.selectList || [row];
			switch (fn) {
				case "sensorData":
					loadSensorData(selected[0]);
					break;
				case "conf":
					configAlarmDialog.detail.sn = row.devSn;
					configAlarmDialog.detail.sensorKey = row.varKey;
					configAlarmDialog.title = `${proxy?.$t("realalarm.dialog_title.config")}（${row.devName || row.devSn}-${row.varKey}）`;
					configAlarmDialog.visible = true;
					break;
				case "execute":
					if (!selected.length) {
						showMsg(proxy?.$t("realalarm.msg.execute"), MessageType.warning);
						return;
					}
					suggestionAlarmDialog.suggestion = "";
					suggestionAlarmDialog.dataList = selected;
					suggestionAlarmDialog.visible = true;
					break;
				case "del":
					if (!selected.length) {
						showMsg(proxy?.$t("realalarm.msg.del"), MessageType.warning);
						return;
					}
					delAlarmInfo(selected.map((e: any) => e.id).join(","));
					break;
			}
		};
		const delAlarmInfo = (ids: string) => {
			ElMessageBox.confirm(proxy?.$t("realalarm.elmsg.confirm"), proxy?.$t("realalarm.elmsg.tip"), { type: "warning" }).then(
				() => {
					delAlarm({ id: ids }).then((res: any) => {
						if (res.code == 200) {
							ElMessage.success(proxy?.$t("realalarm.elmsg.success"));
							proTable.value.getTableList();
						} else {
							ElMessage.error(res.message || proxy?.$t("realalarm.elmsg.error"));
						}
					});
				}
			);
		};

		const configAlarmDialog = reactive({
			visible: false,
			suggestion: "",
			detail: {
				sn: "",
				sensorKey: ""
			},
			title: proxy?.$t("realalarm.dialog_title.config")
		});
		const suggestionAlarmDialog = reactive({
			visible: false,
			suggestion: "",
			dataList: [] as any[],
			title: proxy?.$t("realalarm.dialog_title.suggestion")
		});
		const suggestionAlarm = async () => {
			let id = suggestionAlarmDialog.dataList.map(item => item.id).join(",");
			let suggestion = suggestionAlarmDialog.suggestion;
			let { code, message } = await processAlarm({ id: id, suggestion: suggestion });
			suggestionAlarmDialog.visible = false;
			let ok = showTips(code, proxy?.$t("realalarm.tips.suggestion"), message);
			if (ok) {
				proTable.value.getTableList();
				proTable.value.clearSelection();
			}
		};
		const alarmTypeInfo = ref<any>({});
		async function loadAlarmType(row: any) {
			let { result } = await getDeviceAlarmConfig({ sn: row.devSn, key: row.varKey }, true);
			let conf = (result as any)?.[0] || {};
			let info = conf.warning?.find((item: any) => item.alarmType == row.alarmType);
			alarmTypeInfo.value = info || {};
		}
		return () => {
			return (
				<div class="real-alarm-page ">
					<SensorHistory ref={sensorHistoryEl} />
					<DialogBox title={configAlarmDialog.title} v-model:visible={configAlarmDialog.visible} footerLabel={["关闭"]}>
						{configAlarmDialog.visible ? (
							<ConfigDetail
								sn={configAlarmDialog.detail.sn}
								sensorKey={configAlarmDialog.detail.sensorKey}
								title={configAlarmDialog.title}
							/>
						) : null}
					</DialogBox>
					<DialogBox
						width="600px"
						title={suggestionAlarmDialog.title}
						v-model:visible={suggestionAlarmDialog.visible}
						onConfirm={() => suggestionAlarm()}
					>
						<el-form label-width="100px">
							<el-form-item label={proxy?.$t("realalarm.form_label.device")}>
								{suggestionAlarmDialog.dataList.map((item: any) => item.devName || item.devSn).join(", ")}
							</el-form-item>
							{suggestionAlarmDialog.dataList.length == 1 ? (
								<>
									<el-form-item label={proxy?.$t("realalarm.form_label.info")}>
										{suggestionAlarmDialog.dataList[0].varName || suggestionAlarmDialog.dataList[0].detailvarKey}
									</el-form-item>
									<el-form-item label={proxy?.$t("realalarm.form_label.value")}>
										{suggestionAlarmDialog.dataList[0].varValue}
									</el-form-item>
									<el-form-item label={proxy?.$t("realalarm.form_label.time")}>
										{duration(dayjs(suggestionAlarmDialog.dataList[0].createTime))}
									</el-form-item>
								</>
							) : null}
							<el-form-item label={proxy?.$t("realalarm.form_label.suggestion")}>
								<el-input
									type="textarea"
									v-model={suggestionAlarmDialog.suggestion}
									placeholder={proxy?.$t("realalarm.input_placeholder.suggestion")}
									rows={6}
								></el-input>
							</el-form-item>
						</el-form>
					</DialogBox>

					<AlarmSearch v-model:collapsed={initParam.collapsed} param={initParam} onSubmit={() => proTable.value.getTableList()} />
					<div class="mt-1 ignore-search-split">
						<ProTable
							height="550"
							ref={proTable}
							custSearch
							onSearchCollapsed={val => (initParam.collapsed = val)}
							columns={columns}
							initParam={initParam}
							title={buttonsList.value.length ? "" : proxy?.$t("realalarm.tab_title.real")}
							requestApi={getTableList}
							dataCallback={dataCallback}
						>
							{{
								tableHeader: (scope: any) => {
									return buttonsList.value?.map((item: any) => {
										return (
											<el-button class={`iconfont ${item.icon}`} onClick={() => handerBtn(item.path, scope)} type={item.btnClass}>
												{item.menuName}
											</el-button>
										);
									});
								},
								devSn: (scope: any) => {
									return (
										<el-link type="primary" onClick={() => gotoPage(RouterPath.deviceDetail, { sn: scope.row.devSn })}>
											<div class="master-title">{scope.row.devName || scope.row.devSn}</div>
										</el-link>
									);
								},
								createTime: (scope: any) => {
									return dataFormat("datetime", scope.row.createTime);
								},
								updateTime: (scope: any) => {
									return dataFormat("datetime", scope.row.updateTime);
								},
								alarmType: (scope: any) => {
									return (
										<el-popover show-after={500} width="300px" onShow={() => loadAlarmType(scope.row)} title="告警参数">
											{{
												reference() {
													return (
														<el-link type="primary" onClick={() => handerBtn("conf", scope.row)}>
															{scope.row.alarmType}
														</el-link>
													);
												},
												default() {
													return (
														<div class="leading-8 alarm-type-popover">
															<div class="flex">
																<div class="label">{proxy?.$t("realalarm.form_label.alarm_type")}</div>
																<div class="text">{alarmTypeInfo.value?.alarmType}</div>
															</div>
															<div class="flex">
																<div class="label">{proxy?.$t("realalarm.form_label.alarm_mode")}</div>
																<div class="text">{(useAlarmMode(alarmTypeInfo.value?.warningMode) as IAlarmParam).label}</div>
															</div>
															<div class="flex">
																<div class="label">{proxy?.$t("realalarm.form_label.is_error")}</div>
																<div class="text">
																	<el-tag type={alarmTypeInfo.value?.isError ? "danger" : "info"}>
																		{alarmTypeInfo.value?.isError
																			? proxy?.$t("realalarm.is_error.yes")
																			: proxy?.$t("realalarm.is_error.no")}
																	</el-tag>
																</div>
															</div>
															<div class="flex">
																<div class="label">{proxy?.$t("realalarm.form_label.auto_done")}</div>
																<div class="text">
																	<el-tag type={alarmTypeInfo.value?.autoDone ? "info" : "danger"}>
																		{alarmTypeInfo.value?.autoDone
																			? proxy?.$t("realalarm.is_auto.auto")
																			: proxy?.$t("realalarm.is_auto.manual")}
																	</el-tag>
																</div>
															</div>
															<div class="flex">
																<div class="label">{proxy?.$t("realalarm.form_label.trigger_type")}</div>
																<div class="text">
																	<el-tag type={alarmTypeInfo.value?.triggerType ? "info" : "danger"}>
																		{alarmTypeInfo.value?.triggerType
																			? proxy?.$t("realalarm.trigger_type.first")
																			: proxy?.$t("realalarm.trigger_type.every")}
																	</el-tag>
																</div>
															</div>
														</div>
													);
												}
											}}
										</el-popover>
									);
								},
								duration: (scope: any) => {
									return duration(dayjs(scope.row.createTime));
								},
								varName: (scope: any) => {
									return (
										<el-popover show-after={500} width="300px">
											{{
												reference: () => {
													return (
														<span>
															<i class="iconfont iconalert-circle"></i>
															<span
																class="pl-1 cursor-pointer primary-color"
																onClick={() => {
																	handerBtn("sensorData", scope.row);
																}}
															>
																{scope.row.varName || scope.row.varKey}
															</span>
														</span>
													);
												},
												default: () => {
													return (
														<div>
															<div class="flex leading-6">
																<div>变量标识：</div>
																<div class="pl-1">{scope.row.varKey}</div>
															</div>
															<div class="flex leading-6">
																<div>变量名称：</div>
																<div class="pl-1">{scope.row.varName}</div>
															</div>
														</div>
													);
												}
											}}
										</el-popover>
									);
								},
								warningMode: (scope: any) => {
									return Object.values(dicts.warningMode).find(item => item.value == scope.row.warningMode)?.label;
								},
								level: (scope: any) => {
									return <AlarmLevel v-model={scope.row.level} />;
								},
								isError: (scope: any) => {
									return Object.values(dicts.isError).find(item => item.value == scope.row.isError)?.label;
								},
								autoDone: (scope: any) => {
									return Object.values(dicts.autoDone).find(item => item.value == scope.row.autoDone)?.label;
								},
								triggerType: (scope: any) => {
									return Object.values(dicts.triggerType).find(item => item.value == scope.row.triggerType)?.label;
								},
								warningType: (scope: any) => {
									return Object.values(dicts.warningType).find(item => item.value == scope.row.warningType)?.label;
								},
								operation: (scope: any) => {
									return (
										<el-link type="primary" onClick={() => handerBtn("execute", scope.row)}>
											{proxy?.$t("realalarm.link.execute")}
										</el-link>
									);
								}
							}}
						</ProTable>
					</div>
				</div>
			);
		};
	}
});
